//
//  QDWebViewController.m
//  QDMetroClient
//
//  Created by YueWen on 2019/2/24.
//  Copyright © 2019 YueWen. All rights reserved.
//

#import "QDWebViewController.h"
#import "QDMetroClient-Swift.h"



@interface QDWebViewController()



@end

@implementation QDWebViewController

- (BOOL)autoRequestUrlAtViewDidLoad {
    return false;
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.shouldShare = false;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = UIColor.whiteColor;
    self.progressView.tintColor = QDSColorTheme;
    
    if (self.hasParentNavigationController) {//设置导航
        
        UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
        
        self.navigationItem.backBarButtonItem = barButtonItem;
        
        [self.navigationController.navigationBar setBackIndicatorImage:self.backIndicatorImageName.ritl_image.ritl_renderOriginImage];
        
        [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:self.backIndicatorImageName.ritl_image.ritl_renderOriginImage];
        
        [self setDefaultNavigationBarWhenHasParentNavigationController];
        
        //设置分享按钮
        if (self.shouldShare) {
            
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:@"share_gray".ritl_image style:UIBarButtonItemStylePlain target:self action:@selector(shareForHtml)];
        }
    }
    
    //注册
    [WebViewJavascriptBridge enableLogging];
    self.bridge = [WebViewJavascriptBridge bridgeForWebView:self.webView];
    [self.bridge setWebViewDelegate:self];
    [self registerBridge];
    [self requestUrl];
}



- (BOOL)hasParentNavigationController {
    return [self.parentViewController isKindOfClass:[UINavigationController class]];
}


- (NSString *)backIndicatorImageName {
    return @"nav_back_default";
}


- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    
    if (UIDevice.currentDevice.systemVersion.floatValue > 11.0){
        
        self.webView.ritl_originY = RITL_DefaultNaviBarHeight;
        self.webView.ritl_height = self.view.ritl_height - RITL_DefaultNaviBarHeight;
        
    }else {
        
        CGFloat height = UIScreen.mainScreen.ritl_height - RITL_DefaultNaviBarHeight;
        if(height != self.webView.ritl_height){
            self.webView.ritl_height = UIScreen.mainScreen.ritl_height - RITL_DefaultNaviBarHeight;
        }
    }
}



-(void)registerBridge {
    
    // 注册相关方法
    [_bridge registerHandler:@"getTokenForH5" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(QDUserInfoModelObjc.token);
    }];
    
    
    [_bridge registerHandler:@"getVersionForH5" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(NSDictionary.ritl_version);
    }];
    
    
    [_bridge registerHandler:@"getPhoneForH5" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(QDUserInfoModelObjc.phone);
    }];
}


- (void)dealloc {
    
    //清除所有的缓存
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] modifiedSince:[NSDate dateWithTimeIntervalSince1970:0] completionHandler:^{}];
    
    NSLog(@"\n\n%@ is dealloc\n\n",NSStringFromClass(self.class));
}




#pragma mark - <WKNavigationDelegate>

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL    *url     = navigationAction.request.URL;
    NSString * urlStr = url.absoluteString;
    
    if ([url.host isEqualToString:@"itunes.apple.com"] && [[UIApplication sharedApplication] canOpenURL:url]) {
        [[UIApplication sharedApplication] openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel); return;
    }
    
    NSLog(@"scheme = %@",url.scheme);
    
    if ([url.scheme isEqualToString:@"qdmetro"]) {
        NSString *functionName = [urlStr substringFromIndex:[urlStr rangeOfString:@"//"].location + 2];
        NSRange range          = [functionName rangeOfString:@"="];
        NSString *mid          = @"";
        
        if (range.location != NSNotFound) {
            mid = [functionName substringFromIndex:range.location+1];
        }
        
        if ([functionName containsString:@"favorite"]) {
            [self favoriteClick:mid];
        }
        
        if ([functionName containsString:@"thumbup"]) {
            [self thumbupClick:mid];
        }
        
        if ([functionName containsString:@"enroll_activity"]) {
            [self handleCustomAction:mid];
        }
        
        if ([functionName containsString:@"loginForH5"]) {
            [self loginForH5];
        }
        
        if ([functionName containsString:@"agreementForH5"]) {
            [self agreementForH5];
        }
        decisionHandler(WKNavigationActionPolicyCancel); return;
    }
    
    
    //支付宝
    if ([url.scheme containsString:@"alipays"]) {
        
        if (@available(iOS 10.0, *)) {
            [UIApplication.sharedApplication openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @false} completionHandler:^(BOOL success) {}];
        }else {
            [UIApplication.sharedApplication openURL:url];
        }
    }
    

    
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
//    NSInteger i = 0;
    
}


- (void)thumbupClick:(NSString *)mid {
    [self thumbupWithId:mid];
}


- (void)favoriteClick:(NSString *)mid {
    [self favoriteWithId:mid];
}


- (void)handleCustomAction:(NSString *)mid {}



- (void)loginForH5 {
    [self checkLogin:^{}];
}


- (void)agreementForH5 {
    
}

/// 分享
- (void)shareForHtml {
    [self shareAction];
}

@end
